<?php
namespace App\Http\Common;

use DB;
use Cache;
use Session;
/**
 * 系统权限节点读取器
 * Class NodeService
 * @package extend
 * @author Anyon <zoujingli@qq.com>
 * @date 2017/05/08 11:28
 */
class NodeService 
{
    /**
     * 检查用户节点权限
     * @param string $node 节点
     * @return bool
     */
    public static function checkAuthNode($node) {
        list($module, $controller, $action) = explode('/', str_replace(['?', '=', '&'], '/', $node . '///'));
        $auth_node = strtolower(trim("{$module}/{$controller}/{$action}", '/'));
        if (session('user.username') === 'admin' || stripos($node, 'admin/index') === 0) {
            return true;
        }
        if (!in_array($auth_node, self::getAuthNode())) {
            return true;
        }
        return in_array($auth_node, (array) session('user.nodes'));
    }


    /**
     * 获取授权节点
     * @return array
     */
    public static function getAuthNode() {
        $nodes = Cache::get('need_access_node');
        if (empty($nodes)) {
            $nodes = Db::name('system_node')->where('is_auth', '1')->select('node')->all();
            Cache::forever('need_access_node', $nodes);
        }
        return $nodes;
    }
}